package 队列;

/**
 * @description:
 * @author: ChenYunChou
 * @time: 2021/5/2 2021
 */
public class MyCircularQueue {
    /**
     * 已经使用元素个数
     */
    private int used = 0;

    /**
     * 第一个元素所在位置
     */
    private int front = 0;

    /**
     * rear是enQueue可在存放的位置
     * [front,rear)
     */
    private int rear = 0;

    /**
     * 循环队列最多可以存放的元素个数
     */
    private int capacity = 0;

    /**
     * 循环队列的存储空间
     */
    private int[] a = null;

    private MyCircularQueue(int k){
        //初始化
        capacity = k;
        a = new int[capacity];
    }

    public boolean enQueue(int value){
        //如果已经放满了
        if (isFull()){
            return false;
        }
        //如果没有放满，那么a[rear]用来存放新进来的元素
        a[rear] = value;
        //rear取模
        rear = (rear + 1) % capacity;
        used++;
        return true;
    }

    public boolean deQueue(){
        if (isEmpty()){
            return false;
        }
        int ret = a[front];
        front = (front + 1) % capacity;
        used--;
        return true;
    }

    public int Front(){
        if (isEmpty()){
            return -1;
        }
        return a[front];
    }

    public int Rear(){
        if (isEmpty()){
            return -1;
        }
        int tail = (rear - 1 + this.capacity) % capacity;
        return a[tail];
    }

    private boolean isEmpty() {
        return used == 0;
    }

    private boolean isFull() {
        return used == capacity;
    }

}
